package com.jasiri.project.ui.process.page

import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jasiri.project.R
import com.jasiri.project.adapter.ProcessCommonAdapter
import com.jasiri.project.databinding.PageProcessCommonBinding
import com.jasiri.project.pro.ProFragment
import com.jasiri.project.ui.process.activity.ProcessActivity
import com.jasiri.project.utils.DensityUtils
import com.jasiri.project.utils.dialog.BirthdayDialog
import com.jasiri.project.utils.dialog.CommonPopupWindow
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.event.track.TrackEventManager
import com.jasiri.project.utils.helper.ActivityStackHelper
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.log.HHLog
import com.jasiri.project.utils.rv.LinearDecoration
import com.jasiri.lib.baseadapter.JasiriBaseAdapterUtil.getColor
import com.jasiri.lib.baseadapter.JasiriOnItemChildClickListener
import com.jasiri.project.app.App
import com.jasiri.project.lib.dev.JasiriSysDataHelper
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/18 11:29
 * @Annotation：流程通用列表样式
 */
class CommonPage(): ProFragment() {
    private var _binding: PageProcessCommonBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    var data: JSONObject? = null

    //内容列表
    var mCommonAdapter: ProcessCommonAdapter? = null
    var mSelectPosition = -1

    //出生日期选择
    private var mBirthdayDialog: BirthdayDialog? = null

    constructor(data: JSONObject): this(){
        this.data = data
    }

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageProcessCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.transparent))
        initRvList()
    }

    override fun initListener() {
        //下一步
        _binding?.btnNext?.setOnClickListener {
            _binding?.root?.clearFocus()
            if (!isAllowSubmit() || data == null){
                showToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }

            data?.let {
                val params = JSONObject().addCommonParams().apply {
                    put("path",it.optString("apiUrl").replace("/",""))
                }
                mCommonAdapter?.let { adapter ->
                    for (i in 0..< adapter.itemCount){
                        val item = adapter.getItem(i)
                        if (item.has("selectItem")){
                            val selectItem = item.optJSONObject("selectItem")
                            if (selectItem != null){
                                params.put(item.optString("paramName"),selectItem.optString("value"))
                            }
                        }
                    }
                }
                //立即上报
                TrackEventManager.trackEventNow(String.format(EventType.CLICK.CLICK_STEP_XX_NEXT,it.optString("stepTitle")),"")
                //上报位置和陀螺仪数据
                JasiriSysDataHelper.onCheckSubmitDataByTypes(App.instance(), arrayListOf("T11","T12"),it.optString("stepTitle"))

                HHLog.e(">>>>>>submit data>>>>>>>$params")
                val act = context as ProcessActivity
                act.submitAction(params)
            }
        }
    }

    override fun initData() {
        if (data == null){
            ActivityStackHelper.finishActivity(ProcessActivity::class.java)
            return
        }

        _binding?.stepTipsLayout?.visibility = View.GONE
        _binding?.contactAddOne?.visibility = View.GONE
        _binding?.approvedTipsLayout?.visibility = View.GONE
        _binding?.amountPlusLayout?.visibility = View.GONE
        data?.let {
            val stepTitle = it.optString("stepTitle")
            if ("personal_info" == stepTitle){
                _binding?.textStepTips?.setTextColor(getColor(R.color.FF4C8FFB))
                val showKey = getString(R.string.process_personal_info_tips_key)
                val showText = String.format(getString(R.string.process_personal_info_tips),showKey)
                val startIndex = showText.indexOf(showKey)
                val dataSecuritySpannable = SpannableString(showText)
                dataSecuritySpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF0040A8)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                //加粗
                dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                _binding?.textStepTips?.text = dataSecuritySpannable
                _binding?.stepTipsIcon?.setImageResource(R.mipmap.img_process_personal_info_tips_icon)
                _binding?.stepTipsLayout?.setBackgroundResource(R.drawable.process_personal_info_tips_bg)
                _binding?.stepTipsLayout?.visibility = View.VISIBLE

                _binding?.textAmountPlus?.text = String.format(getString(R.string.process_loan_amount_plus),it.optString("limitAmount"))
                _binding?.amountPlusLayout?.visibility = View.VISIBLE
            }

            val dataList = arrayListOf<JSONObject>()
            val dataArray = it.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..< dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
            }
            addEvent(String.format(EventType.PAGE.PAGE_STEP_COMMON_XX_START,it.optString("stepTitle")),"")
            mCommonAdapter?.data = dataList
        }
    }

    /**
     * 初始化页面内容列表
     */
    private fun initRvList() {
        _binding?.rvCommon?.setHasFixedSize(true)
        _binding?.rvCommon?.isNestedScrollingEnabled = false
        _binding?.rvCommon?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.rvCommon?.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        _binding?.rvCommon?.addItemDecoration(LinearDecoration(0, 0, 0, topDecoration))
        mCommonAdapter = ProcessCommonAdapter(_binding?.rvCommon)
        _binding?.rvCommon?.adapter = mCommonAdapter
        _binding?.rvCommon?.itemAnimator = DefaultItemAnimator()
        mCommonAdapter?.setOnItemChildClickListener(onItemClickListener)
    }

    /**
     * 选择
     */
    private val onItemClickListener =
        JasiriOnItemChildClickListener { parent, childView, position ->
            _binding?.root?.clearFocus()
            mSelectPosition = position
            mCommonAdapter?.let { adapter ->
                val item = adapter.getItem(position)
                when (item.optString("action")) {
                    "DATE_PICK" -> {//时间选择
                        showBirthDialog()
                    }

                    "SELECT" -> {//选择
                        val dataList = arrayListOf<JSONObject>()
                        val dataArray = item.optJSONArray("values")
                        dataArray?.let {
                            for (i in 0..<it.length()) {
                                dataList.add(it.optJSONObject(i))
                            }
                        }
                        showSelectPopupwindow(childView, dataList)
                    }
                }
            }
        }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        _binding?.let {
            val selectPopup = CommonPopupWindow(requireContext())
            selectPopup.setWindowWidth(view.width + DensityUtils.dp2px(10f))
            selectPopup.setSelectItemListener(object : CommonPopupWindow.IItemClickListener {
                //完成
                override fun onConfirmAction(data: JSONObject?) {
                    mCommonAdapter?.let { adapter ->
                        val item = adapter.getItem(mSelectPosition)
                        item.put("selectItem",data)
                        adapter.notifyItemChanged(mSelectPosition)

                        val subRemark = "${data?.optString("value")}$$${data?.optString("duration")}"
                        addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                    }
                }
                //关闭监听
                override fun onDismissListener() {
                }
            })
            selectPopup.show(view, it.root)
            selectPopup.setBrandList(dataList)
        }
    }

    /**
     * 选择出生日期
     */
    private fun showBirthDialog(){
        if (mBirthdayDialog == null){
            mBirthdayDialog = BirthdayDialog(context,"",object : BirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    mCommonAdapter?.let {
                        //可根据需要自行截取数据显示
                        val item = it.getItem(mSelectPosition)
                        val obj = JSONObject()
                        obj.put("title",selectDate.optString("showDate"))
                        obj.put("title_sw",selectDate.optString("showDate"))
                        obj.put("value",selectDate.optString("subDate"))
                        item.put("selectItem",obj)
                        it.notifyItemChanged(mSelectPosition)

                        addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT,item.optString("paramName")),selectDate.optString("subDate"))
                    }
                }
            })
        }
        mBirthdayDialog?.show()
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        mCommonAdapter?.let { adapter ->
            for (i in 0..< adapter.itemCount){
                val item = adapter.getItem(i)
                //存在 isMust && isMust == ”NO“  非必填
                if (item.has("isMust") && item.optString("isMust") == "NO"){
                    continue
                }
                //必填 && 没有内容 || 内容为空
                if (!item.has("selectItem")){
                    isAllow = false
                    break
                }
                val selectItem = item.optJSONObject("selectItem")
                if (selectItem == null){
                    isAllow = false
                    break
                }
                if (selectItem.optString("value","").isEmpty()){
                    isAllow = false
                    break
                }
            }
        }
        return isAllow
    }

    override fun onDestroy() {
        super.onDestroy()
        data?.let {
            addEvent(String.format(EventType.PAGE.PAGE_STEP_COMMON_XX_END,it.optString("stepTitle")),"")
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}